<?php
namespace app\app\controller\v2;
use app\app\Appbase;
use app\common\model\Msg as MsgModel;
use app\common\model\MsgUser;
use app\common\model\MsgOrder;
use app\common\model\MsgSystem;
use app\common\model\MsgSystemRead;

class Msg extends Appbase 
{
	
	/**
	*获取未读消息列表
	* /app/v3/msg/getList
	* 需要登录 
	* @is_need_login true
	* @method all
	*/
	public function getList(){
		$request =  request();
		$uid = $request->userId;
		$shopId = $request->shopId;
		try {
			//TODO 系统消息未读数量
	      	$system = MsgModel::where('notice_type',3)
		      	->where('recive_id',$request->shopId ? 0 : $uid)
		      	->sum('unread_num') -  MsgSystemRead::where('uid',$uid)->count();
			$system = $system < 0 ? 0 : $system;
			//TODO 交易消息未读数量
	        $order =  MsgModel::where('recive_id','shop_'.$shopId)
		        ->where('notice_type',2)
		        ->sum('unread_num');
			//TODO 消息列表
	        $msgList = MsgModel::userUnreadMsgList( 'shop_'.$shopId );
			//返回
			return $this->ReSucess(compact('system','order','msgList','shopMsgList') );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	*获取订单消息
	* /app/v3/msg/getOrderMsg
	* 需要登录 
	* @is_need_login true
	* @method all
	*/
	public function getOrderMsg($pageIndex=1,$pageSize=10){
		$request =  request();
		if( empty($request->userInfo['roles_id']) ){
			$uid = $request->userId;
		}else{
			$uid = 'shop_'.$request->shopInfo['id'];
		}
		try {
	        $result = MsgModel::getOrderMsg($uid,$pageIndex,$pageSize);
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	*获取系统消息
	* /app/v3/msg/getSystemMsg
	* 需要登录 
	* @is_need_login true
	* @method all
	*/
	public function getSystemMsg($pageIndex=1,$pageSize=10){
		$request =  request();
		if( empty($request->userInfo['roles_id']) ){
			$uid = $request->userId;
		}else{
			$uid = $request->shopInfo['uid'];
			//$uid = 'shop_'.$request->shopInfo['id'];
		}
		try {
	        $result = MsgModel::getSystemMsg($uid,$pageIndex,$pageSize);
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	*获取客服id
	* /app/v2/msg/getCsdId
	* 需要登录 
	* @is_need_login true
	* @method all
	*/
	public function getCsdId(){
		$request =  request();
		$uid = $request->userId;
		
		try {
			
			$value = '';
			
			$csd = db('systemUser')->where("is_csd=1 and is_admin !=1")->column('user_guid');
			
			$history = db('msgUser')
				->where('send_id',$uid)
				->where('length(recive_id)>10')
				->order('add_time desc')
				->field('recive_id')
				->find();
			
			if( $history &&  in_array($history['recive_id'],$csd) ){
				$value = $history['recive_id'];
			}else{
				$value = $csd[array_rand($csd,1)];
			}
			
			if(!$value){
				$value = db('systemUser')->where("is_admin =1")->value('user_guid');
			}
			
			$result = db('systemUser')->where("user_guid",$value)
				->field('user_guid as id')
				->field('user_name as name')
				->field(
					db("systemUpload")->alias('c') 
						->where('c.file_buss_type','用户信息')
						->where('c.file_type','头像')
						->where('c.file_guid = user_guid')
						->field("concat('".APP_PATH."/"."',c.file_path ) as file_path")
						->limit(0,1)
						->union("SELECT '".APP_PATH."/Public/images/user_img.jpg' as file_path")
						->buildSql() ." img"
				)
				->find();
			
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	*获取聊天页面列表
	* /app/v3/msg/getChatLog
	* 需要登录 
	* @is_need_login true
	* @method all
	*/
	public function getUserChatList($recive_id,$pageIndex=1,$pageSize=10){
		$request =  request();
		$uid = $request->userId;
		$shopId = $request->shopId;
		if(!$recive_id){
			return $this->ReError( "参数错误" );	
		}
		try {
	        $result = MsgModel::getUserChatList('shop_'.$shopId,$recive_id,$pageIndex,$pageSize);
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	*发送消息
	* /app/v3/msg/sendMsg
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function sendMsg(){
		$request =  request();
		$shopId = $request->shopId;
		$param = $request->post();
		$staffId = $request->userInfo['roles_id'] ? $request->userId : '';
		
		//TODO 获取post参数
    	list($reciveId,$content,$ctType,$relationId) = [
    		$param['recive_id'] ?: 0,
    		$param['content'] ?: '',
    		$param['content_type'] ?: 1,
    		$param['relation_id'] ?: '',
    	];
		
		if(!$reciveId){
			return $this->ReError( "参数错误" );	
		}
		
		try {
			$db = new MsgModel;
	        $result = $db->send('shop_'.$shopId,$reciveId,$content,$ctType,$relationId,1,$staffId);
			if($result === false){
				return $this->ReError( $db->errorInfo );	
			}
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
}



